// 统计数据页面脚本

document.addEventListener('DOMContentLoaded', function() {
    // 初始化统计页面
    initStatisticsPage();
    
    // 添加页面可见性变化事件监听器，当页面变为可见时刷新数据
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') {
            loadData();
        }
    });
});

// 全局变量
const state = {
    period: 'daily', // daily, weekly, monthly, yearly
    currentDate: getCurrentDate(), // 使用修正后的当前日期
    statistics: [],
    goals: [],
    focusSessions: [],
    charts: {}
};

// 初始化统计页面
function initStatisticsPage() {
    // 确保当前日期是正确的
    validateCurrentDate();
    
    // 注册时间段切换按钮事件
    const periodButtons = document.querySelectorAll('.period-btn');
    periodButtons.forEach(button => {
        button.addEventListener('click', function() {
            switchPeriod(this.getAttribute('data-period'));
        });
    });
    
    // 注册前一个周期和后一个周期按钮事件
    document.getElementById('prev-period').addEventListener('click', navigateToPrevPeriod);
    document.getElementById('next-period').addEventListener('click', navigateToNextPeriod);
    
    // 加载数据并渲染
    loadData();
}

// 验证当前日期是否合理，避免使用未来日期
function validateCurrentDate() {
    const now = getCurrentDate(); // 使用全局修正函数
    const currentYear = now.getFullYear();
    
    console.log('统计页面 - 验证日期 - 修正后年份:', currentYear);
    
    // 强制将state.currentDate的年份设置为修正后的年份
    if (state.currentDate.getFullYear() !== currentYear) {
        console.warn('统计页面 - 日期年份已修正:', 
                    state.currentDate.getFullYear(), '->', currentYear);
        
        // 创建新日期对象，保留月日，修改年份
        const correctedDate = new Date(state.currentDate);
        correctedDate.setFullYear(currentYear);
        state.currentDate = correctedDate;
    }
    
    // 更新统计数据中的日期
    if (state.statistics && state.statistics.length > 0) {
        state.statistics.forEach(stat => {
            if (stat.date) {
                const statDate = new Date(stat.date);
                if (statDate.getFullYear() !== currentYear) {
                    // 调整统计数据日期到当前年份
                    stat.date = new Date(
                        currentYear, 
                        statDate.getMonth(), 
                        statDate.getDate()
                    ).toISOString().split('T')[0];
                }
            }
        });
    }
}

// 切换时间段
function switchPeriod(period) {
    // 更新按钮状态
    const buttons = document.querySelectorAll('.period-btn');
    buttons.forEach(button => {
        button.classList.toggle('active', button.getAttribute('data-period') === period);
    });
    
    // 更新状态
    state.period = period;
    
    // 重置当前日期到今天（仅改变显示的周期，不改变日期）
    state.currentDate = new Date();
    
    // 更新数据和视图
    loadData();
}

// 导航到前一个周期
function navigateToPrevPeriod() {
    switch (state.period) {
        case 'daily':
            state.currentDate.setDate(state.currentDate.getDate() - 1);
            break;
        case 'weekly':
            state.currentDate.setDate(state.currentDate.getDate() - 7);
            break;
        case 'monthly':
            state.currentDate.setMonth(state.currentDate.getMonth() - 1);
            break;
        case 'yearly':
            state.currentDate.setFullYear(state.currentDate.getFullYear() - 1);
            break;
    }
    
    loadData();
}

// 导航到后一个周期
function navigateToNextPeriod() {
    const today = new Date();
    let shouldUpdate = true;
    
    switch (state.period) {
        case 'daily':
            state.currentDate.setDate(state.currentDate.getDate() + 1);
            // 不允许查看未来的日期
            if (state.currentDate > today) {
                state.currentDate = new Date(today);
                shouldUpdate = false;
            }
            break;
        case 'weekly':
            state.currentDate.setDate(state.currentDate.getDate() + 7);
            if (state.currentDate > today) {
                state.currentDate = new Date(today);
                shouldUpdate = false;
            }
            break;
        case 'monthly':
            state.currentDate.setMonth(state.currentDate.getMonth() + 1);
            if (state.currentDate > today) {
                state.currentDate = new Date(today);
                shouldUpdate = false;
            }
            break;
        case 'yearly':
            state.currentDate.setFullYear(state.currentDate.getFullYear() + 1);
            if (state.currentDate > today) {
                state.currentDate = new Date(today);
                shouldUpdate = false;
            }
            break;
    }
    
    if (shouldUpdate) {
        loadData();
    }
}

// 获取当前周期的日期范围
function getPeriodRange() {
    const currentDate = state.currentDate;
    let startDate, endDate;
    
    switch (state.period) {
        case 'daily':
            // 当天的开始和结束
            startDate = new Date(currentDate);
            startDate.setHours(0, 0, 0, 0);
            
            endDate = new Date(currentDate);
            endDate.setHours(23, 59, 59, 999);
            break;
            
        case 'weekly':
            // 本周的开始（星期日）和结束（星期六）
            startDate = new Date(currentDate);
            const day = startDate.getDay(); // 0 = 周日, 6 = 周六
            startDate.setDate(startDate.getDate() - day);
            startDate.setHours(0, 0, 0, 0);
            
            endDate = new Date(startDate);
            endDate.setDate(endDate.getDate() + 6);
            endDate.setHours(23, 59, 59, 999);
            break;
            
        case 'monthly':
            // 本月的开始和结束
            startDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
            startDate.setHours(0, 0, 0, 0);
            
            endDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
            endDate.setHours(23, 59, 59, 999);
            break;
            
        case 'yearly':
            // 本年的开始和结束
            startDate = new Date(currentDate.getFullYear(), 0, 1);
            startDate.setHours(0, 0, 0, 0);
            
            endDate = new Date(currentDate.getFullYear(), 11, 31);
            endDate.setHours(23, 59, 59, 999);
            break;
    }
    
    return { startDate, endDate };
}

// 加载数据并渲染
async function loadData() {
    try {
        // 确保当前日期是正确的
        validateCurrentDate();
        
        // 加载统计数据
        const statsResponse = await api('/statistics');
        state.statistics = statsResponse;
        
        // 加载目标数据
        const goalsResponse = await api('/goals');
        state.goals = goalsResponse;
        
        // 加载专注会话数据
        const sessionsResponse = await api('/focus-sessions');
        state.focusSessions = sessionsResponse;
        
        // 确保图表对象已初始化
        if (!state.charts) {
            state.charts = {};
        }
        
        // 更新时间段显示
        updatePeriodDisplay();
        
        // 根据当前选择的时间段筛选数据
        const { filteredStats, filteredSessions, filteredGoals } = filterDataByPeriod();
        
        // 更新统计卡片
        updateStatisticsCards(filteredStats, filteredSessions, filteredGoals);
        
        // 更新图表
        try {
            updateCharts(filteredStats, filteredSessions, filteredGoals);
        } catch (chartError) {
            console.error('更新图表时出错:', chartError);
        }
        
        // 生成洞察
        generateInsights(filteredStats, filteredSessions, filteredGoals);
        
    } catch (error) {
        console.error('加载数据失败:', error);
    }
}

// 将loadData函数设置为全局可用
window.loadData = loadData;

// 更新周期显示
function updatePeriodDisplay() {
    const periodElement = document.getElementById('current-period');
    let periodText = '';
    
    // 获取当前日期范围
    const { startDate, endDate } = getPeriodRange();
    
    // 确保使用的是当前实际年份
    const realYear = new Date().getFullYear();
    
    switch (state.period) {
        case 'daily':
            // 使用当前实际年份替代可能错误的年份
            periodText = `${realYear}年 ${startDate.getMonth() + 1}月${startDate.getDate()}日`;
            break;
        case 'weekly':
            periodText = `${startDate.getMonth() + 1}月${startDate.getDate()}日 - ${endDate.getMonth() + 1}月${endDate.getDate()}日`;
            break;
        case 'monthly':
            periodText = `${realYear}年 ${startDate.getMonth() + 1}月`;
            break;
        case 'yearly':
            periodText = `${realYear}年`;
            break;
    }
    
    periodElement.textContent = periodText;
}

// 按周期筛选数据
function filterDataByPeriod() {
    // 获取当前周期的日期范围
    const { startDate, endDate } = getPeriodRange();
    
    // 筛选统计数据
    const filteredStats = state.statistics.filter(stat => {
        const statDate = new Date(stat.date);
        return statDate >= startDate && statDate <= endDate;
    });
    
    // 筛选专注会话数据
    const filteredSessions = state.focusSessions.filter(session => {
        const sessionDate = new Date(session.start_time);
        return sessionDate >= startDate && sessionDate <= endDate;
    });
    
    // 筛选目标数据 (筛选在当前时间段内有更新的目标)
    const filteredGoals = state.goals.filter(goal => {
        // 检查目标是否在当前时间段内创建或更新
        const createdAt = new Date(goal.created_at);
        const updatedAt = new Date(goal.updated_at);
        return (createdAt >= startDate && createdAt <= endDate) || 
               (updatedAt >= startDate && updatedAt <= endDate);
    });
    
    return { filteredStats, filteredSessions, filteredGoals };
}

// 更新统计卡片
function updateStatisticsCards(filteredStats, filteredSessions, filteredGoals) {
    // 计算总专注时间（分钟）
    const totalFocusTime = filteredSessions
        .filter(session => session.type === 'focus' && session.completed)
        .reduce((total, session) => total + Math.floor(session.duration / 60), 0);
    
    // 计算专注次数
    const focusCount = filteredSessions
        .filter(session => session.type === 'focus' && session.completed)
        .length;
    
    // 计算完成目标数
    const completedGoalsCount = filteredGoals
        .filter(goal => goal.completed)
        .length;
    
    // 计算专注效率
    let efficiency = 0;
    if (filteredStats.length > 0) {
        // 如果有统计数据，使用平均效率
        efficiency = filteredStats.reduce((sum, stat) => sum + (stat.efficiency || 0), 0) / filteredStats.length;
    } else if (focusCount > 0) {
        // 如果没有统计数据但有专注会话，计算效率
        // 假设理想情况是每个专注时段都完成了25分钟
        const idealFocusTime = focusCount * 25;
        efficiency = (totalFocusTime / idealFocusTime) * 100;
    }
    
    // 更新DOM
    document.getElementById('total-focus-time').textContent = `${totalFocusTime} 分钟`;
    document.getElementById('total-focus-count').textContent = focusCount;
    document.getElementById('completed-goals').textContent = completedGoalsCount;
    document.getElementById('focus-efficiency').textContent = `${Math.round(efficiency)}%`;
}

// 更新图表
function updateCharts(filteredStats, filteredSessions, filteredGoals) {
    // 准备图表数据
    const focusTimeData = prepareFocusTimeChartData(filteredStats, filteredSessions);
    const goalsCompletionData = prepareGoalsCompletionChartData(filteredGoals);
    const focusHeatmapData = prepareFocusHeatmapData(filteredSessions);
    
    // 更新或创建专注时间分布图表
    updateFocusTimeChart(focusTimeData);
    
    // 更新或创建目标完成情况图表
    updateGoalsCompletionChart(goalsCompletionData);
    
    // 更新或创建专注热力图
    updateFocusHeatmapChart(focusHeatmapData);
}

// 准备专注时间图表数据
function prepareFocusTimeChartData(filteredStats, filteredSessions) {
    const labels = [];
    const data = [];
    
    switch (state.period) {
        case 'daily':
            // 按小时显示
            for (let hour = 0; hour < 24; hour++) {
                labels.push(`${hour}:00`);
                
                // 计算该小时的专注时间总和
                const hourlyFocusTime = filteredSessions
                    .filter(session => {
                        const sessionHour = new Date(session.start_time).getHours();
                        return sessionHour === hour && session.type === 'focus' && session.completed;
                    })
                    .reduce((total, session) => total + Math.floor(session.duration / 60), 0);
                
                data.push(hourlyFocusTime);
            }
            break;
            
        case 'weekly':
            // 按天显示
            const { start } = getPeriodRange();
            const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            
            for (let day = 0; day < 7; day++) {
                const date = new Date(start);
                date.setDate(date.getDate() + day);
                
                labels.push(daysOfWeek[date.getDay()]);
                
                // 找到对应日期的统计数据
                const dayStat = filteredStats.find(stat => {
                    const statDate = new Date(stat.date);
                    return statDate.getDate() === date.getDate() && 
                           statDate.getMonth() === date.getMonth() && 
                           statDate.getFullYear() === date.getFullYear();
                });
                
                data.push(dayStat ? dayStat.focus_time : 0);
            }
            break;
            
        case 'monthly':
            // 按周显示
            const { start: monthStart, end: monthEnd } = getPeriodRange();
            const weekCount = Math.ceil((monthEnd - monthStart) / (7 * 24 * 60 * 60 * 1000));
            
            for (let week = 0; week < weekCount; week++) {
                const weekStartDate = new Date(monthStart);
                weekStartDate.setDate(weekStartDate.getDate() + week * 7);
                
                const weekEndDate = new Date(weekStartDate);
                weekEndDate.setDate(weekEndDate.getDate() + 6);
                
                labels.push(`第${week + 1}周`);
                
                // 计算该周的专注时间总和
                const weeklyFocusTime = filteredStats
                    .filter(stat => {
                        const statDate = new Date(stat.date);
                        return statDate >= weekStartDate && statDate <= weekEndDate;
                    })
                    .reduce((total, stat) => total + stat.focus_time, 0);
                
                data.push(weeklyFocusTime);
            }
            break;
            
        case 'yearly':
            // 按月显示
            const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', 
                              '七月', '八月', '九月', '十月', '十一月', '十二月'];
            
            for (let month = 0; month < 12; month++) {
                labels.push(monthNames[month]);
                
                // 找到该月的统计数据
                const monthlyFocusTime = filteredStats
                    .filter(stat => {
                        const statDate = new Date(stat.date);
                        return statDate.getMonth() === month;
                    })
                    .reduce((total, stat) => total + stat.focus_time, 0);
                
                data.push(monthlyFocusTime);
            }
            break;
    }
    
    return { labels, data };
}

// 准备目标完成情况图表数据
function prepareGoalsCompletionChartData(filteredGoals) {
    // 按类别统计目标完成情况
    const categories = ['work', 'study', 'personal', 'other'];
    const categoryNames = {
        'work': '工作',
        'study': '学习',
        'personal': '个人',
        'other': '其他'
    };
    
    const labels = categories.map(cat => categoryNames[cat]);
    const completedData = [];
    const inProgressData = [];
    
    categories.forEach(category => {
        const goalsInCategory = filteredGoals.filter(goal => goal.category === category);
        const completedGoals = goalsInCategory.filter(goal => goal.completed);
        
        completedData.push(completedGoals.length);
        inProgressData.push(goalsInCategory.length - completedGoals.length);
    });
    
    return { labels, completedData, inProgressData };
}

// 准备专注热力图数据
function prepareFocusHeatmapData(filteredSessions) {
    // 按小时和星期几统计专注次数
    const heatmapData = Array(7).fill().map(() => Array(24).fill(0));
    
    filteredSessions.forEach(session => {
        if (session.type === 'focus' && session.completed) {
            const date = new Date(session.start_time);
            const dayOfWeek = date.getDay(); // 0 = 星期日, 6 = 星期六
            const hour = date.getHours();
            
            heatmapData[dayOfWeek][hour]++;
        }
    });
    
    return heatmapData;
}

// 更新专注时间分布图表
function updateFocusTimeChart(chartData) {
    const ctx = document.getElementById('focus-time-chart').getContext('2d');
    
    if (state.charts.focusTimeChart) {
        state.charts.focusTimeChart.destroy();
    }
    
    state.charts.focusTimeChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: chartData.labels,
            datasets: [{
                label: '专注时间（分钟）',
                data: chartData.data,
                backgroundColor: 'rgba(74, 110, 224, 0.7)',
                borderColor: 'rgba(74, 110, 224, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '分钟'
                    }
                }
            }
        }
    });
}

// 更新目标完成情况图表
function updateGoalsCompletionChart(chartData) {
    const ctx = document.getElementById('goals-completion-chart').getContext('2d');
    
    if (state.charts.goalsCompletionChart) {
        state.charts.goalsCompletionChart.destroy();
    }
    
    state.charts.goalsCompletionChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: chartData.labels,
            datasets: [
                {
                    label: '已完成',
                    data: chartData.completedData,
                    backgroundColor: 'rgba(40, 199, 111, 0.7)',
                    borderColor: 'rgba(40, 199, 111, 1)',
                    borderWidth: 1
                },
                {
                    label: '进行中',
                    data: chartData.inProgressData,
                    backgroundColor: 'rgba(228, 232, 247, 0.7)',
                    borderColor: 'rgba(228, 232, 247, 1)',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '目标数量'
                    },
                    stacked: true
                },
                x: {
                    stacked: true
                }
            }
        }
    });
}

// 更新专注热力图
function updateFocusHeatmapChart(heatmapData) {
    const ctx = document.getElementById('focus-heatmap-chart').getContext('2d');
    
    // 销毁旧图表以避免Canvas重用错误
    if (state.charts.focusHeatmapChart) {
        state.charts.focusHeatmapChart.destroy();
    }
    
    // 准备热力图数据
    const hoursOfDay = Array.from({length: 24}, (_, i) => `${i}:00`);
    const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    
    // 创建数据点
    const data = [];
    heatmapData.forEach((hours, dayIndex) => {
        hours.forEach((value, hourIndex) => {
            if (value > 0) { // 只添加有数据的点
                data.push({
                    x: hoursOfDay[hourIndex],
                    y: daysOfWeek[dayIndex],
                    v: value
                });
            }
        });
    });
    
    // 创建新图表
    try {
        state.charts.focusHeatmapChart = new Chart(ctx, {
            type: 'scatter',
            data: {
                datasets: [{
                    data: data.map(point => ({
                        x: point.x,
                        y: point.y,
                        r: Math.max(5, point.v * 3)  // 半径根据值大小变化
                    })),
                    backgroundColor: function(context) {
                        if (!context.raw) return 'rgba(74, 110, 224, 0.2)';
                        const value = context.raw.r / 3 || 0;
                        const alpha = Math.min(0.8, Math.max(0.1, value / 10));
                        return `rgba(74, 110, 224, ${alpha})`;
                    },
                    borderColor: 'rgba(74, 110, 224, 0.8)',
                    borderWidth: 1,
                    hitRadius: 5,
                    hoverRadius: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        type: 'category',
                        labels: daysOfWeek
                    },
                    x: {
                        type: 'category',
                        labels: hoursOfDay.filter((_, i) => i % 3 === 0)  // 每3小时显示一个标签
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const point = data[context.dataIndex];
                                return `${point.y} ${point.x}: ${point.v} 次专注`;
                            }
                        }
                    },
                    legend: {
                        display: false
                    }
                }
            }
        });
    } catch (error) {
        console.error('创建热力图失败:', error);
    }
}

// 生成洞察
function generateInsights(filteredStats, filteredSessions, filteredGoals) {
    const insightsList = document.getElementById('insights-list');
    insightsList.innerHTML = '';
    
    // 如果没有数据，显示提示
    if (filteredSessions.length === 0) {
        const emptyInsight = document.createElement('div');
        emptyInsight.className = 'insight-card';
        emptyInsight.innerHTML = `
            <div class="insight-card-header">
                <div class="insight-icon">
                    <i class="fas fa-info-circle"></i>
                </div>
                <div class="insight-title">暂无数据</div>
            </div>
            <div class="insight-content">
                该时间段内没有专注记录，开始您的专注之旅吧！
            </div>
        `;
        insightsList.appendChild(emptyInsight);
        return;
    }
    
    // 生成多个洞察
    const insights = [];
    
    // 洞察1: 最佳专注时段
    if (filteredSessions.length > 0) {
        // 按小时统计专注时间
        const hourlyFocus = Array(24).fill(0);
        filteredSessions.forEach(session => {
            if (session.type === 'focus' && session.completed) {
                const hour = new Date(session.start_time).getHours();
                hourlyFocus[hour] += session.duration / 60; // 转为分钟
            }
        });
        
        // 找出专注时间最长的时段
        let bestHour = 0;
        let maxFocusTime = 0;
        
        hourlyFocus.forEach((time, hour) => {
            if (time > maxFocusTime) {
                maxFocusTime = time;
                bestHour = hour;
            }
        });
        
        if (maxFocusTime > 0) {
            insights.push({
                title: '最佳专注时段',
                icon: 'fa-clock',
                content: `您的最佳专注时间是 <span class="insight-highlight">${bestHour}:00 - ${bestHour + 1}:00</span>，共专注了 <span class="insight-highlight">${Math.round(maxFocusTime)}</span> 分钟。在这个时段安排重要工作可能会取得更好的效果。`
            });
        }
    }
    
    // 洞察2: 专注习惯
    if (filteredSessions.length > 5) {
        // 计算平均专注时长
        const focusSessions = filteredSessions.filter(s => s.type === 'focus' && s.completed);
        const avgFocusDuration = focusSessions.reduce((sum, s) => sum + s.duration, 0) / focusSessions.length / 60;
        
        // 根据平均专注时长给出建议
        let habitInsight = '';
        if (avgFocusDuration < 15) {
            habitInsight = `您的平均专注时长为 <span class="insight-highlight">${Math.round(avgFocusDuration)}</span> 分钟，相对较短。尝试逐渐增加专注时间，可以提高工作效率。`;
        } else if (avgFocusDuration >= 15 && avgFocusDuration < 25) {
            habitInsight = `您的平均专注时长为 <span class="insight-highlight">${Math.round(avgFocusDuration)}</span> 分钟，接近理想的25分钟番茄工作法时长。继续保持这个节奏！`;
        } else {
            habitInsight = `您的平均专注时长为 <span class="insight-highlight">${Math.round(avgFocusDuration)}</span> 分钟，超过了标准的25分钟番茄工作法时长。您的专注能力很强！`;
        }
        
        insights.push({
            title: '专注习惯分析',
            icon: 'fa-chart-line',
            content: habitInsight
        });
    }
    
    // 洞察3: 目标完成情况
    if (filteredGoals.length > 0) {
        const completedGoals = filteredGoals.filter(g => g.completed);
        const completionRate = (completedGoals.length / filteredGoals.length) * 100;
        
        let goalInsight = '';
        if (completionRate < 30) {
            goalInsight = `您的目标完成率为 <span class="insight-highlight">${Math.round(completionRate)}%</span>。考虑设置更小、更可实现的目标，逐步提高完成率。`;
        } else if (completionRate >= 30 && completionRate < 70) {
            goalInsight = `您的目标完成率为 <span class="insight-highlight">${Math.round(completionRate)}%</span>，表现不错。继续保持这个节奏，同时可以尝试细分大目标为小任务。`;
        } else {
            goalInsight = `您的目标完成率为 <span class="insight-highlight">${Math.round(completionRate)}%</span>，非常优秀！您有很好的目标管理能力。`;
        }
        
        insights.push({
            title: '目标达成分析',
            icon: 'fa-bullseye',
            content: goalInsight
        });
    }
    
    // 洞察4: 专注趋势
    if (state.period !== 'daily' && filteredStats.length > 1) {
        // 分析专注时间的趋势
        const sortedStats = [...filteredStats].sort((a, b) => new Date(a.date) - new Date(b.date));
        
        if (sortedStats.length >= 2) {
            const firstStat = sortedStats[0];
            const lastStat = sortedStats[sortedStats.length - 1];
            
            const trendPercent = firstStat.focus_time > 0 
                ? ((lastStat.focus_time - firstStat.focus_time) / firstStat.focus_time) * 100
                : 0;
            
            let trendInsight = '';
            if (trendPercent > 10) {
                trendInsight = `与${state.period === 'weekly' ? '本周初' : state.period === 'monthly' ? '本月初' : '今年初'}相比，您的专注时间增长了 <span class="insight-highlight">${Math.round(trendPercent)}%</span>。继续保持这个优秀的上升趋势！`;
            } else if (trendPercent < -10) {
                trendInsight = `与${state.period === 'weekly' ? '本周初' : state.period === 'monthly' ? '本月初' : '今年初'}相比，您的专注时间下降了 <span class="insight-highlight">${Math.round(Math.abs(trendPercent))}%</span>。可以尝试重新规划您的专注策略。`;
            } else {
                trendInsight = `与${state.period === 'weekly' ? '本周初' : state.period === 'monthly' ? '本月初' : '今年初'}相比，您的专注时间基本保持稳定。保持良好的节奏！`;
            }
            
            insights.push({
                title: '专注趋势分析',
                icon: 'fa-chart-bar',
                content: trendInsight
            });
        }
    }
    
    // 渲染洞察卡片
    insights.forEach(insight => {
        const insightCard = document.createElement('div');
        insightCard.className = 'insight-card';
        insightCard.innerHTML = `
            <div class="insight-card-header">
                <div class="insight-icon">
                    <i class="fas ${insight.icon}"></i>
                </div>
                <div class="insight-title">${insight.title}</div>
            </div>
            <div class="insight-content">
                ${insight.content}
            </div>
        `;
        insightsList.appendChild(insightCard);
    });
    
    // 如果没有生成洞察，显示默认消息
    if (insights.length === 0) {
        const defaultInsight = document.createElement('div');
        defaultInsight.className = 'insight-card';
        defaultInsight.innerHTML = `
            <div class="insight-card-header">
                <div class="insight-icon">
                    <i class="fas fa-lightbulb"></i>
                </div>
                <div class="insight-title">继续积累数据</div>
            </div>
            <div class="insight-content">
                随着更多专注数据的积累，我们将为您提供个性化的专注洞察和建议。继续坚持，保持专注！
            </div>
        `;
        insightsList.appendChild(defaultInsight);
    }
}

// 日期格式化辅助函数
function formatDate(date, format) {
    const d = new Date(date);
    
    const year = d.getFullYear();
    const month = d.getMonth() + 1;
    const day = d.getDate();
    
    // 修复格式问题，确保年份和月份之间有空格
    if (format.includes('年M')) {
        // 替换为年份+空格+月份的格式
        return `${year}年 ${month}月${format.includes('d') ? day + '日' : ''}`;
    }
    
    // 其他格式处理
    format = format.replace('yyyy', year);
    format = format.replace('年', year + '年');
    format = format.replace('M', month);
    format = format.replace('d', day);
    
    return format;
} 